import { DataConfig } from './DataConfig';
import { bam } from './BundleAssetsManager';
import { BaseManager } from './../libs/rxjs/cc3/BaseManager';
import { _decorator, color, director, System } from 'cc';
import { xlsxArrayToMapEx } from '../libs/utils/XlsxArrayTools';
import { jsonObjectTree } from '../libs/utils/JsonFromNodeXlsxTools';
import { map } from '../libs/rxjs/internal/operators/map';
import { toNumberList } from '../libs/utils/toNumberList';
import { ReactiveCommand } from '../libs/rxjs/cc3/ReactiveCommand';
import { deepclone } from '../libs/utils/deepclone/deepclone';
import { randomChoose } from '../libs/utils/RandomChooseTools';
import { gm } from './GameManager';
import { sdk } from '../SDK/SDKManager';
import { sdkadm } from '../SDK/SDKVideoAdManager';
import { am } from './AudioManager';
import { udm } from './UserDataManager';
import { sdkrm } from '../SDK/SDKRecorderManager';
import { AdFlag } from '../SDK/ADFlag';
const { ccclass, property } = _decorator;

export type CompartmentInfo = Array<number[]>; // [[0;0],[0;0;0]]

export type XlsxInfo = {
    Stage: {
        index: Record<number, {
            ID: number, StagePrefabName: string, Time: number, Time2: number, InfTime: number,
            Items3x: number[], Items6x: number[], Items9x: number[], Items12x: number[], Items15x: number[], Items18x: number[],
            _Total: number,
            compartments: Record<string, CompartmentInfo>,
        }>,
        main: { version: number, totalCount: number },
        map: Record<number, { ID: number, MapTo: number }>
    },
    Misc: {
        main: {
            reviveTimes: number, timeUpExTime: number, foreverExTime: number,
            infTimeNeed: number, tipWaitTime: number, tipWaitTime2: number, tipPropWaitTime: number,
            adCompleteMapNeed: number, comboTime: number,
            shoppingWait: number, shoppingLast: number,
        },
        heart: {
            version: number, maxCount: number, consume: number, recoverInterval: number, recoverCount: number, initCount: number, adIncCount: number,
            infNeedCount: number,
        },
    },
    Prop: {
        index: Record<'hammer' | 'superhammer' | 'fairywand' | 'blackhole' | 'magnet' | 'shopping', {
            Key: string, Init: number, StageNum: number, StageLimit: number, Enabled: boolean
        }>,
    },
    Item: {
        index: Record<number, {
            ID: number, Skin1: string, Skin1Q: string, Skin2: string, Skin2Q: string
        }>
    },
    Skin: {
        index: Record<number, {
            ID: number, AdCount: number
        }>
    },
}

@ccclass('DataManager')
class DataManager extends BaseManager {

    public static instance: DataManager;
    static ID = 'data_system';
    get logColorOverride() { return color().fromHEX('#EEDDCC') };

    static registerSystem() {
        director.unregisterSystem(director.getSystem(DataManager.ID));
        director.registerSystem(DataManager.ID, dm, System.Priority.MEDIUM);
        dm.init();
    }

    onInitManager() {
        this.log('onInitManager', this.timestamp);
    }

    xlsx: XlsxInfo = null;
    xlsxInitializedCommand = ReactiveCommand.Create<never>();
    initXlsx() {
        this.xlsx = {} as any;
        for (let key in bam.xlsxJsonAssets) {
            this.xlsx[key] = {} as any;
            switch (key) {
                case 'Stage':
                    bam.xlsxJsonAssets[key].json.forEach(element => {
                        const { name, data } = element;
                        switch (name) {
                            case 'index':
                            case 'map':
                                this.xlsx[key][name] = xlsxArrayToMapEx(data);
                                break;
                            case 'main':
                                this.xlsx[key][name] = jsonObjectTree(data);
                                break;
                        }
                    });
                    DataConfig.maxStageCount = this.xlsx.Stage.main.totalCount;
                    break;
                case 'Misc':
                    bam.xlsxJsonAssets[key].json.forEach(element => {
                        const { name, data } = element;
                        this.xlsx[key][name] = jsonObjectTree(data);
                    });
                    break;
            }
        }
        this.xlsxInitializedCommand.execute();
    }

    showAdsFor(flag: AdFlag) {
        sdk.report('rewardad_start', { type: flag });
        am.stopBgm();
        sdkrm.pauseRecorder();
        return sdkadm.showAds().pipe(map(_ => {
            sdkrm.resumeRecorder();
            udm.bgmOn.again();
            if (_) {
                sdk.report('rewardad_over', { type: flag, success: 1 });
                return true;
            } else {
                sdk.report('rewardad_over', { type: flag, success: 0 });
                return false;
            }
        }));
    }

    skipInLayerRandom = false; // 生成时，是否跳过层内乱序，一般关卡为false，而教程关卡，比如第一关，需要固定下来，就填true

}

globalThis.DataManager = DataManager;

export const dm = DataManager.instance = new DataManager();